package com.chongyahhh.security.security.common;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author chongyahhh
 * 通用用户信息
 * 通过 SecurityContextHolder.getContext().getAuthentication() 便可获取当前用户信息
 * 用法：
 * CommonAuthentication user = (CommonAuthentication)SecurityContextHolder.getContext().getAuthentication();
 */
public class CommonAuthentication extends AbstractAuthenticationToken {
    // 用户id
    private String userId;

    // 用户名
    private Object principal;

    // 密码
    private Object credentials;

    // 附加属性（如微信小程序后端对应的 openId）
    private Map<String, Object> extraMap;

    public CommonAuthentication(Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        extraMap = new HashMap<>();
    }

    // 不验证权限
    public CommonAuthentication(Object principal, Object credentials, String userId) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        this.userId = userId;
        this.setAuthenticated(false);
        extraMap = new HashMap<>();
    }

    // 验证权限
    public CommonAuthentication(Object principal, Object credentials, String userId, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        this.userId = userId;
        super.setAuthenticated(true);
        extraMap = new HashMap<>();
    }

    @Override
    public Object getCredentials() {
        return credentials;
    }

    @Override
    public Object getPrincipal() {
        return principal;
    }

    public String getUserId(){
        return this.userId;
    }

    // 添加附加属性
    public void setExtra(String key, Object extra){
        extraMap.put(key, extra);
    }

    // 获取附加属性
    public Object getExtra(String key){
        return extraMap.get(key);
    }

    // 移除附加属性
    public void removeExtra(String key){
        extraMap.remove(key);
    }
}
